import React, { useState, forwardRef } from 'react'
import { isSuccess } from '@/utils/request';
import { Form, message, Modal, Spin, Select, Checkbox } from 'antd'
import If from '@/components/If';

import { saveGlobalData } from '@/services/salaryManage/salaryChart';

import NumberInput from '@/pages/SalaryManage/components/NumberInput';

import CustomPopover from '../component/CustomPopover';
import SalaryItemsSelect from '../component/SalaryItemsSelect';

import { showTypeMap, overviewTypeMap, itemTypeMap, totalAmountType } from '../paramMap';

import styles from '../style.less'

// 薪资项过滤
const changeSalaryValues = (rule, value, callback) => {
    if (value.length > 6 || value.length < 2) {
        callback('最少选择2个，最多选择6个')
    }
    callback()
}

// 设置子模块
const SettingItems = forwardRef(({ title, children, form, configData, changeHandle }) => {
    const { getFieldDecorator, getFieldValue } = form
    const { globalType,
            isContainKpi,
            isEnable,
            remindNum,
            showType,
        warnNum } = configData

    const remindChangeValidator = (rule, value, callback, key) => {
        const contrastVal = getFieldValue(globalType)[key]
        if (contrastVal.length === 0 || value.length === 0) {
            callback()
        }
        if (value <= 0) {
            callback(`${overviewTypeMap[globalType]}提醒值需大于0`)
        }

        if (value >= contrastVal) {
            callback(`${overviewTypeMap[globalType]}提醒值需要小于警示值`)
        }
        callback()
    }

    const warnChangeValidator = (rule, value, callback, key) => {
        const contrastVal = getFieldValue(globalType)[key]
        if (contrastVal.length === 0 || value.length === 0) {
            callback()
        }
        if (value <= 0) {
            callback(`${overviewTypeMap[globalType]}警示值需大于0`)
        }

        if (value <= contrastVal) {
            callback(`${overviewTypeMap[globalType]}警示值需要大于提醒值`)
        }
        callback()
    }

    return (
        <div className={styles.salaryItemBox}>
            <div className={styles.salaryItemTitle}>
                <Checkbox
                    disabled={globalType === totalAmountType}
                    checked={isEnable}
                    onChange={() => changeHandle('isEnable', globalType)}>{title}</Checkbox>
            </div>
            { isEnable ?
                <div>
                    {children}
                    <Form.Item label="展示">
                        {getFieldDecorator(`${globalType}.showType`, {
                        initialValue: showType,
                        rules: [{ required: true, message: '请选择' }]
                    })(
                        <Select style={{ width: 210 }} placeholder="请选择">
                            {
                                Object.entries(showTypeMap).map(([key, name]) =>
                                    <Select.Option key={key} value={key}>{name}</Select.Option>)
                            }
                        </Select>
                    )}
                        &nbsp;&nbsp;{
                        globalType === totalAmountType ? <Checkbox
                            checked={isContainKpi}
                            onChange={() => changeHandle('isContainKpi', globalType)}>含绩效薪资</Checkbox> : null
                    }
                    </Form.Item>
                    <Form.Item label="上升/下降">
                        超过&nbsp;&nbsp;{getFieldDecorator(`${globalType}.warnNum`, {
                        initialValue: warnNum,
                        rules: [{ required: true, message: `请设置${overviewTypeMap[globalType]}警示值` }, {
                            validator: (rule, value, callback) => warnChangeValidator(rule, value, callback, 'remindNum')
                        }]
                    })(
                        <NumberInput style={{ width: 120 }} decimalPlaces={2} suffix="%" placeholder="请输入"/>
                    )}&nbsp;&nbsp;警示
                    </Form.Item>
                    <Form.Item label=" " colon={false}>
                        超过&nbsp;&nbsp;{getFieldDecorator(`${globalType}.remindNum`, {
                        initialValue: remindNum,
                            rules: [{ required: true, message: `请设置${overviewTypeMap[globalType]}提醒值` }, {
                            validator: (rule, value, callback) => remindChangeValidator(rule, value, callback, 'warnNum')
                        }]
                    })(
                        <NumberInput style={{ width: 120 }} decimalPlaces={2} suffix="%" placeholder="请输入"/>
                    )}&nbsp;&nbsp;提醒
                    </Form.Item>
                </div> : null
            }
        </div>
    )
})

const TotalSettingModal = Form.create()(({ form, visible, onOk, onCancel, model, changeHandle, organizationCode }) => {
    const [loading, setLoading] = useState(false);

    const { validateFieldsAndScroll, getFieldDecorator } = form

    const handleOk = () => {
        validateFieldsAndScroll(async (errors, values) => {
            if (!errors) {
                const formList = model?.globalItemInfoList?.map(item => {
                    const { globalType } = item
                    const formItem = values[globalType] || {}
                    return {
                        ...item,
                        ...formItem
                    }
                })
                setLoading(true)
                const globalResponse = await saveGlobalData({
                    ...model,
                    organizationCode,
                    globalItemInfoList: formList
                })

                setLoading(false)
                if (isSuccess(globalResponse)) {
                    message.success(globalResponse.msg)
                    onOk(formList)
                } else {
                    message.error(globalResponse.msg)
                }
            }
        })
    };

    // 合计金额介绍
    const TitleWrapper = ({ item }) => (
        <span>
            {overviewTypeMap[item.globalType]}
            {item.globalType === totalAmountType ? <CustomPopover content="合计金额固定分析项包括：实发金额、薪资总额、税前薪资" /> : null}
        </span>
    )

    return (
        <Modal
            title="总览设置"
            visible={visible}
            okText="确定"
            onOk={handleOk}
            cancelText="取消"
            onCancel={onCancel}
            confirmLoading={loading}
        >
            <Spin spinning={loading}>
                <div style={{ maxHeight: 600, overflowY: 'auto' }}>
                    <Form labelCol={{ span: 6 }} hideRequiredMark wrapperCol={{ span: 18 }}>
                        {
                            model?.globalItemInfoList?.map(item =>
                                <SettingItems
                                    form={form}
                                    changeHandle={changeHandle}
                                    configData={item}
                                    key={item.globalType}
                                    title={<TitleWrapper item={item} />}>
                                    {
                                        item.globalType === totalAmountType || !item.isEnable ? null : (
                                            <Form.Item label="薪资项">
                                                {getFieldDecorator(`${item.globalType}.salaryItemIdList`, {
                                                    initialValue: item.salaryItemIdList,
                                                    rules: [{
                                                        required: true,
                                                        message: '请选择'
                                                    }, {
                                                        validator: changeSalaryValues
                                                    }]
                                                })(
                                                    <SalaryItemsSelect
                                                        organizationCode={organizationCode}
                                                        itemType={itemTypeMap[item.globalType]}
                                                        getPopupContainer={trigger => trigger.parentElement}
                                                        mode="multiple"
                                                        maxTagCount={1}
                                                        maxTagTextLength={8}
                                                        extraType={1}
                                                        style={{ width: 210 }}
                                                        treeCheckable
                                                        multiple
                                                    />
                                                )}
                                            </Form.Item>
                                        )
                                    }
                                </SettingItems>)
                            }
                    </Form>
                </div>
            </Spin>
        </Modal>
    );
});
TotalSettingModal.displayName = 'TotalSettingModal';

/**
 *总览配置
 * @param organizationCode
 * @param globalInfo
 * @param changeFn
 */
const useTotalSetting = (organizationCode, globalInfo, changeFn) => {
    // 显示分配
    const [showTotalSetting, setShowTotalSetting] = useState(false);
    const [modalData, setModalData] = useState({});

    // 展示弹窗
    const onShowTotalSetting = () => {
        setModalData(JSON.parse(JSON.stringify(globalInfo)))
        setShowTotalSetting(true);
    };
    // 保存按钮
    const onTotalSetting = formValues => {
        setShowTotalSetting(false)
        changeFn(formValues)
    };

    // 切换checkbox
    const changeHandle = (key, type) => {
        const newData = modalData?.globalItemInfoList?.map(({ globalType, isEnable, isContainKpi, ...otherItem }) => ({
            ...otherItem,
            globalType,
            isEnable: key === 'isEnable' && type === globalType ? !isEnable : isEnable,
            isContainKpi: key === 'isContainKpi' && type === globalType ? !isContainKpi : isContainKpi
        }))
        setModalData({
            ...modalData,
            globalItemInfoList: newData
        })
    }

    return {
        onShowTotalSetting,
        render() {
            return (
                <>
                    <If condition={showTotalSetting}>
                        <TotalSettingModal
                            visible={showTotalSetting}
                            onOk={onTotalSetting}
                            organizationCode={organizationCode}
                            onCancel={() => setShowTotalSetting(false)}
                            changeHandle={changeHandle}
                            model={modalData}
                        />
                    </If>
                </>
            );
        }
    };
};

export default useTotalSetting;
